package com.molichuxing.framework.interceptor;

import com.molichuxing.framework.interceptor.dynamicdatasource.DbContextHolder;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.List;

/**
 * 
 * @Title: DynamicTransactionInterceptor
 * @Description: 动态事务拦截器，拦截方法后，加入数据源切换的功能
 * @Author: 林亿建
 * @DateTime: 2017年9月6日
 * @Version: 1.0.0
 */
public class DynamicTransactionInterceptor extends TransactionInterceptor {

  private List<String> writeMthods;
  
  public DynamicTransactionInterceptor(){ }
  
  public DynamicTransactionInterceptor(List<String> writeMthods){
    this.writeMthods = writeMthods;
  }
  
  @Override
  public Object invoke(MethodInvocation invocation) throws Throwable {
    /**后期需要扩展DBContextHolder.setJdbcType()中传递的数据源的值为列*/
    //设置数据源
    if(isWriteMethod(invocation.getMethod().getName())){
      DbContextHolder.setJdbcType("writeDataSource");
    }else{
      //设置只读数据源
      DbContextHolder.setJdbcType("readDataSource");
    }
    return super.invoke(invocation);
  }
  
  /**
   * 
   * @Description:根据方法名判断是否为写数据库操作
   * @param methodName
   * @return 是否为写数据库方法
   */
  private boolean isWriteMethod(String methodName){
    if("".equals(methodName)){
    return false;
    }
    for(String method:writeMthods){
      if(methodName.startsWith(method)){
        return true;
      }
    }
  return false;
  }

  /** 
   * @Description: 获取writeMthods
   * @return writeMthods
   */
  public List<String> getwriteMthods() {
    return writeMthods;
  }

  /** 
   * 设置writeMthods
   * @param writeMthods 
   */
  public void setwriteMthods(List<String> writeMthods) {
    this.writeMthods = writeMthods;
  }
  
}
